﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using System.Windows.Media.Animation;
using PRScreenWithKinect.Model;

namespace PRScreenWithKinect
{
	/// <summary>s
	/// Interaction logic for News.xaml
	/// </summary>
	public partial class News : UserControl,UserControlInterfaceForGesture
	{
        enum Catagory
        {
            All,Jobs=1,Scholarship=2,Awards=3
        }

        private QueryDB _query; 
        private ArrayList controllerElement;
        private Grid prevMenu;
        private UIElement hitElement = null;
        private UIElement hittedElement = null;
        private Double focusOpacity = 0.7, defaultOpacity = 0.3;
        private SolidColorBrush focusColor = Brushes.Orange,defaultColor = Brushes.White;
        private int pageIndex = 0;
        private int mainController;
        private string[] monthArray = new string[12] { "ม.ค", "ก.พ", "มี.ค", "เม.ษ", "พ.ค", "มิ.ย", "ก.ค", "ส.ค", "ก.ย", "ต.ค", "พ.ย", "ธ.ค" };


        public News()
		{
			this.InitializeComponent();
            Content_Zoom.Visibility = Visibility.Hidden;

            /// Create QueryDB
            ///
            _query = new QueryDB();

            // Add Menu to controllerElement ;s
            controllerElement = new ArrayList();
            controllerElement.Add(Menu1);
            controllerElement.Add(Menu2);
            controllerElement.Add(Menu3);
            controllerElement.Add(Menu4);
            controllerElement.Add(CloseZoom);

            mainController = controllerElement.Count;


            // Set Hit Element = menu1 ;
            hittedElement = Menu1;

      
            /// Load Data with Catagory All 
            loadDataFromJSON(Catagory.All);

           
      
		}

        

        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            zoomContent(null);
        }
        public void zoomContent(UIElement obj)
        {
            NewsModel openNews = (NewsModel)((ListBoxItem)obj).DataContext;
           /// Console.WriteLine("Zoom Content i : " +openNews.date);
            _headZoom.Text = openNews.headline;
            _subHeadZoom.Text = string.Format("{0} | {1}", openNews.dateTime, openNews.catagory);
            _contentZoom.Text = openNews.content;

            Content_Zoom.Visibility = Visibility.Visible;
         scrollView.Visibility = Visibility.Hidden;
         pageBulletStack.Visibility = Visibility.Hidden;
        }
        public void closeZoom()
        {
            Content_Zoom.Visibility = Visibility.Hidden;
           scrollView.Visibility = Visibility.Visible;
           pageBulletStack.Visibility = Visibility.Visible;
        }
        private void CloseZoom_MouseDown(object sender, MouseButtonEventArgs e)
        {
            closeZoom();
        }

        
        private void loadDataFromJSON(Catagory c)
        {
           //// Remove all data from controllerElement 
            if (prevMenu != null)
            {
                ((Path)prevMenu.Children[0]).Fill = defaultColor;
                controllerElement.RemoveRange(mainController, controllerElement.Count-mainController);
                viewer.Children.RemoveRange(0, viewer.Children.Count);
                pageIndex = 0;
            }

            if (c == Catagory.All)
            {
                prevMenu = Menu1;

            }else if(c == Catagory.Jobs){
                prevMenu = Menu2;
            }
            else if (c == Catagory.Scholarship)
            {
                prevMenu = Menu3;
            }
            else if (c == Catagory.Awards)
            {
                prevMenu = Menu4;
            }
            
            ((Path)prevMenu.Children[0]).Fill = focusColor;

            //// Get NewsModel[] from DataFactory 
            DataFactory dataFactory = DataFactory.Instance;
            //Console.WriteLine("News  catagory : " + (int)c);
            List<NewsModel> news = dataFactory.getNewsByCatagory((int)c);

            int newsPerPage = 4; 
            int numOfPage = (int)Math.Ceiling(news.Count/(float)newsPerPage);
            //Console.WriteLine("Page Of Data " + numOfPage+ "  " +news.Count);

            for(int i = 0 ; i <numOfPage ; i++)
            {
                ListBox l = new ListBox();
                l.Width = 468;
                l.Height = 280;
                l.AlternationCount = 2;
       
                for (int j = 0; j < newsPerPage; j++)
                {
                    int news_index = i * newsPerPage + j;
                    if (news_index < news.Count)
                    {
                        NewsModel n = news[(i) * newsPerPage + j];
                        n.shortMonth = monthArray[n.dateTime.Month - 1];
                        n.date = n.dateTime.Day;
                        n.longDate = n.dateTime.ToLongDateString();
                        n.catagory = "หมวด " + n.catagory;
                        ListBoxItem it = new ListBoxItem();
                        it.Template = (ControlTemplate)this.Resources["MyDataTemplate"];
                        it.DataContext = n;
                        l.Items.Add(it);
                        controllerElement.Add(it);                 
                    }
                
                }
  
                
                l.BorderThickness = new Thickness(0);
                l.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
                l.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Disabled);
                
                //l.ItemsSource = news;
                //   l.Background = Brushes.Yellow;

            
                viewer.Children.Add(l);
 //Console.WriteLine("News(Constuct) : " + viewer.Children.Count);
                     

            }
           
            createPageBullet(numOfPage);
          //  Console.WriteLine("News(LoadData) : " + c);
        }
        private void createPageBullet(int n)
        {
            pageBulletStack.Children.RemoveRange(0, pageBulletStack.Children.Count);
            for (int i = 0; i < n; i++)
            {
                Ellipse myEllipse = new Ellipse();

                // Create a SolidColorBrush with a red color to fill the 
                // Ellipse with.

                myEllipse.Fill = Brushes.Gray;
                if (i == 0)
                {
                    myEllipse.Opacity = focusOpacity;
                }
                else
                {
                    myEllipse.Opacity = defaultOpacity;
                }
                
   

                // Set the width and height of the Ellipse.
                myEllipse.Width = 20;
                myEllipse.Height = 20;
                myEllipse.Margin = new Thickness(5, 0, 0, 0);
             //   Console.WriteLine("Add Bullet");
                pageBulletStack.Children.Add(myEllipse);
            }
       
            
        }
      

     
        public void finishHold()
        {
            
            if(hitElement.Equals(Menu1))
            {
                loadDataFromJSON(Catagory.All);
                closeZoom();
            }else if(hitElement.Equals(Menu2)){
                loadDataFromJSON(Catagory.Jobs);
                closeZoom();
            }
            else if (hitElement.Equals(Menu3))
            {
                loadDataFromJSON(Catagory.Scholarship);
                closeZoom();
            }
            else if (hitElement.Equals(Menu4))
            {
                loadDataFromJSON(Catagory.Awards);
                closeZoom();
            }
            else if (hitElement.GetType() == typeof(ListBoxItem))
            {
              
                zoomContent(hitElement);
            }
            else if (hitElement.Equals(CloseZoom))
            {
                closeZoom();
            }
            //Console.WriteLine("Type Hit Element : " + hitElement.GetType());
            hittedElement = hitElement;
            hitElement = null;
        }

        public void swipeLeft()
        {
            doSwipe(Swipe.Left);
          
            
        }

        public void swipeRight()
        {
            doSwipe(Swipe.Right);
        }
 

        public void doSwipe(Swipe s)
        {

            if (s == Swipe.Left && pageIndex!= (viewer.Children.Count-1))
            {


               
                pageIndex++;
                pageBulletStack.Children[pageIndex].Opacity = focusOpacity;
                pageBulletStack.Children[pageIndex - 1].Opacity = defaultOpacity;
          
            }
            else if(s== Swipe.Right && pageIndex!=0)
            {
       
                pageIndex--;
                pageBulletStack.Children[pageIndex].Opacity = focusOpacity;
                pageBulletStack.Children[pageIndex +1].Opacity = defaultOpacity;

            }
            scrollView.ScrollToPosition(scrollView.Width * pageIndex, 0);
           
          //  Console.WriteLine("News(doSwipe) : " + pageIndex);
         
        }



        public bool hitTest(Point p, Window w)
        {
            Boolean isHit = false;
            //     Console.WriteLine("===========================");
            foreach (UIElement c in controllerElement)
            {
                Point RhandRelativePoint = c.TransformToAncestor(w).Transform(new Point(0, 0));
                Point delta = new Point(p.X - RhandRelativePoint.X, p.Y - RhandRelativePoint.Y);
                if (VisualTreeHelper.HitTest(c, delta) != null)
                {
                    if (c.Equals(hitElement) && !c.Equals(hittedElement))
                    {
                        if (c.GetType() == typeof(ListBoxItem) || c.Equals(CloseZoom))
                        {
                            if (c.GetType() == typeof(ListBoxItem) && scrollView.Visibility == Visibility.Visible)
                            {
                                return true;
                            }

                            if (c.Equals(CloseZoom) && Content_Zoom.Visibility == Visibility.Visible)
                            {
                                return true;
                            }
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }
                    else
                    {

                        hitElement = c;
                        return false;

                    }
                }
            }




            return isHit;
        }
    }
}